package org.saiwen.paul.util;

import org.saiwen.paul.solidity.Storage;
import org.web3j.crypto.Credentials;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.RemoteCall;
import org.web3j.protocol.core.methods.request.Transaction;
import org.web3j.protocol.core.methods.response.EthSendTransaction;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.http.HttpService;
import org.web3j.tx.Contract;
import org.web3j.tx.RawTransactionManager;
import org.web3j.tx.TransactionManager;
import org.web3j.tx.gas.StaticGasProvider;

import java.math.BigInteger;

/**
 * @Author paul.peng
 * @Date 2022/5/10
 * @Version 1.0
 */

public class ContractUtil {

    private static ContractUtil contractUtil = new ContractUtil();
    private ContractUtil(){

    }
    // 公共的、静态的获取实例方法
    public static ContractUtil getInstance() {
        return contractUtil;
    }


    private static String netWorkUrl = "https://ropsten.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161";
    private static String credentialsAddress = "0x21790eF006892Aa6105A2F92A227e6a89c7C4276";
    private static String contractAddress = "0x01344C86a9745EB34B4042E75D1c4499fc861869";


    public static void useContract(){
        try {
            //连接对应的
            Web3j web3 = Web3j.build(new HttpService(netWorkUrl));
            Credentials credentials = Credentials.create(credentialsAddress);
            //链id
            System.out.println(web3.netVersion().send().getNetVersion());
            //测试打印
            System.out.println(credentials.getAddress());
            TransactionManager transactionManager = new RawTransactionManager(
                    web3, credentials,3);
            BigInteger gasPrice = web3.ethGasPrice().send().getGasPrice();
            Storage contract = Storage.load(contractAddress,web3,
                    transactionManager,new StaticGasProvider(gasPrice, Contract.GAS_LIMIT));
            RemoteCall<TransactionReceipt> setWord = contract.store(new BigInteger("1"));
            TransactionReceipt transactionReceipt = setWord.send();
            String transactionHash = transactionReceipt.getTransactionHash();
            System.out.println(transactionHash);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
